package profile

import (
	"log"
	"os"
	"runtime"
	"runtime/pprof"
)

type Profiler struct {
	cpuProfile     *os.File
	memProfile     *os.File
	cpuProfilePath string
	memProfilePath string
}

func (p *Profiler) Start() {
	var err error
	p.cpuProfile, err = os.Create(p.cpuProfilePath)
	if err != nil {
		log.Fatal("Could not create CPU profile: ", err)
	}

	if err = pprof.StartCPUProfile(p.cpuProfile); err != nil {
		log.Fatal("Could not start CPU profile: ", err)
	}
	log.Println("CPU profiling started")
	p.memProfile, err = os.Create(p.memProfilePath)
	if err != nil {
		log.Fatal("Could not create memory profile: ", err)
	}
}

func (p *Profiler) Stop() {
	runtime.GC()
	if err := pprof.WriteHeapProfile(p.memProfile); err != nil {
		log.Fatal("Could not write memory profile: ", err)
	}
	log.Println("Memory profiling completed")
	pprof.StopCPUProfile()
	_ = p.cpuProfile.Close()
	_ = p.memProfile.Close()
}

func NewProfiler(cpuProfilePath, memProfilePath string) *Profiler {
	return &Profiler{
		cpuProfilePath: cpuProfilePath,
		memProfilePath: memProfilePath,
	}
}
